﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace WXWorkSvc.Common.Extensions;

public static class CryptographyExtensions
{
    public static string Sha1Sign(this byte[] inputBytes)
    {
        using var sha = SHA1.Create();
        var bytes = sha.ComputeHash(inputBytes);
        StringBuilder stringBuilder = new StringBuilder();
        foreach (var b in bytes)
            stringBuilder.Append(b.ToString("x2"));
        return stringBuilder.ToString();
    }
    public static byte[] AesDecrypt(this byte[] inputBytes, byte[] key, byte[] iv)
    {

        using var rm = Aes.Create();
        rm.Key = key;
        rm.IV = iv;
        rm.Mode = CipherMode.CBC;
        rm.Padding = PaddingMode.Zeros;
        ICryptoTransform decryptor = rm.CreateDecryptor(rm.Key, rm.IV);

        using MemoryStream ms = new MemoryStream(inputBytes);
        using CryptoStream csDecrypt = new CryptoStream(ms, decryptor, CryptoStreamMode.Read);
        var bytelist = new List<byte>();
        var buffer = new byte[4096];
        var len = 0;
        do
        {
            len = csDecrypt.Read(buffer, 0, buffer.Length);
            if (len > 0)
                bytelist.AddRange(buffer.Take(len));
        } while (len == buffer.Length);

        int pad = (int)bytelist.Last();// [bytelist.Count - 1];
        if (pad < 1 || pad > 32)
        {
            pad = 0;
        }
        //byte[] res = new byte[decrypted.Length - pad];

        return bytelist.Take(bytelist.Count-pad).ToArray();
        //using MemoryStream msDecrypt = new MemoryStream();
        //csDecrypt.CopyTo(msDecrypt);
        //return msDecrypt.ToArray();

        //List<byte> bytelist = new List<byte>();
        //byte[] buffer = new byte[1024];
        //var count = 0;
        //do
        //{
        //    count = csDecrypt.Read(buffer, 0, buffer.Length);
        //    if (count > 0)
        //        bytelist.AddRange(buffer.Take(count));
        //} while (count == 1024);

        //return bytelist.ToArray();
    }


}
